package com.czxy.servlet;

import cn.itcast.servlet.BaseServlet;
import com.alibaba.fastjson.JSON;
import com.czxy.domain.Product;
import com.czxy.service.ProductService;
import com.github.pagehelper.PageInfo;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.List;

@WebServlet("/productServlet")
public class ProductServlet  extends BaseServlet {



    //根据商品id 查询商品信息
    public  String findProductByPid(){
        //接收参数
        String pid = getRequest().getParameter("pid");
        //调用Service 获取结果
        ProductService service = new ProductService();
        Product product = service.findProductByPid(pid);

        //存储request域
        getRequest().setAttribute("product",product);

        //请求转发
        return "/jsp/product_info.jsp";


    }


    //分页显示  商品信息
    public  String findProductByCid(){
        //接收 cid  并接收分页的页码 pageNum
        String cid = getRequest().getParameter("cid");
        String pageNum = getRequest().getParameter("pageNum");
        //设置每页的最多显示商品数
        int  pageSize = 5;
        //调用 Service  获取 该分页下的商品信息 pageInfo
        ProductService service = new ProductService();

        PageInfo pageInfo = service.getProductPageInfo(cid, Integer.parseInt(pageNum), pageSize);

        //把pageInfo存储到request域中
        getRequest().setAttribute("pageInfo",pageInfo);
        //传递当前页面的商品分类id
        getRequest().setAttribute("cid",cid);
        //把请求转发到 product_list.jsp
        return "/jsp/product_list.jsp";






    }





















    /**
     * 获取热门商品信息
     * @throws IOException
     */
    public void findHotProducts() throws IOException {
        //1.调用service  得到list
        ProductService service = new ProductService();
        List<Product> hotProducts = service.findHotProducts();
        //2.list -> json
        String s = JSON.toJSONString(hotProducts);
        //3.响应
        getResponse().getWriter().write(s);
    }

    /**
     * 获取最新商品信息
     * @throws IOException
     */
    public void findNewProducts() throws IOException {
        //1.调用service  得到list
        ProductService service = new ProductService();
        List<Product> newProducts = service.findNewProducts();
        //2.list -> json
        String s = JSON.toJSONString(newProducts);
        //3.响应
        getResponse().getWriter().write(s);
    }
}
